package com.polymorphic多态.polyArray多态数组;

public class polyArray {
    public static void main(String[] args) {
        // 创建一个Person类型的数组，长度为5，
        // 因为Student、Teacher是Person的子类，所以可以向上转型，存储Person、Student、Teacher对象
        Person[] persons = new Person[5];
        persons[0] = new Person("张三", 20);
        persons[1] = new Student("李四", 21, 90);
        persons[2] = new Student("jeck", 41, 60);
        persons[3] = new Teacher("王五", 30, 10000);
        persons[4] = new Teacher("大明", 20, 8000);

        for (int i = 0; i < persons.length; i++) {
            //persons[i]的编译类型是Person，运行类型：JVM根据实际情况来判断是Student、Teacher还是Person
            System.out.println(persons[i].say());
            //动态绑定机制，方法的调用根据运行类型来决定


            /**如果想要调用子类特有的方法，需要向下转型*/
            if (persons[i] instanceof Student) {
                /**向下转型 将编译类型 强转成 Student 便可调用子类特有的方法*/
              //Student stu = (Student) persons[i];
               //stu.study();
                ((Student) persons[i]).study();//简化上面两行；
            }
            else if (persons[i] instanceof Teacher) {
                /**向下转型 将编译类型 强转成 Teacher 便可调用子类特有的方法*/
//                Teacher tea = (Teacher) persons[i];
//                tea.teach();
                ((Teacher) persons[i]).teach();//简化上面两行
            }
            System.out.println("==================================");

        }


    }
}
